package cn.catsdad.auth.util;

import cn.catsdad.dto.UserDTO;
import cn.catsdad.util.StringUtil;
import cn.catsdad.vo.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * spring security工具
 *
 * @author xuyonglong
 * @version V1.0 2023/4/14
 */
public class SecurityUtil {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前登录用户
     *
     * @return 用户
     */
    public static UserDTO getUser() {
        Authentication authentication = getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser();
    }

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 密码验证
     *
     * @param password       真实密码
     * @param encodePassword 加密后密码
     * @return 是否匹配
     */
    public static boolean matchPassword(String password, String encodePassword) {
        return encoder.matches(password, encodePassword);
    }

    /**
     * 密码加密
     *
     * @param rawPassword 原密码
     * @return 加密后密码
     */
    public static String passwordEncode(String rawPassword) {
        if (StringUtil.isNotEmpty(rawPassword)) {
            return encoder.encode(rawPassword);
        }
        return "";
    }


}
